from pprint import pprint

from django import http
from django.core.paginator import Paginator
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from goods.models import GoodsCategory
from goods.models import SKU
from goods.models import SpecificationOption

from utils import constants
from utils.goods import breadcrumb
from utils.category import category


class GoosListView(View):
    def get(self, request, category_id, page_num):

        # 1、获取排序方式
        sort = request.GET.get("sort", "default")

        if sort == "price":
            my_sort = "price"
        elif sort == "hot":
            my_sort = "-sales"
        else:
            my_sort = "create_time"

        # 分类
        categories_dict = category()

        # 面包屑导航
        categorys = GoodsCategory.objects.get(id=category_id)
        cate_dict = breadcrumb(categorys)

        # 列表页商品数据
        # 查询id值对应的所有sku数据
        try:
            all_sku = categorys.sku_set.filter(is_launched=True).order_by(my_sort)
        except Exception as e:
            print(e)

        paginator = Paginator(all_sku, constants.GOODS_LIST_LIMIT)
        try:
            page_data = paginator.page(page_num)
        except Exception as e:
            return render(request, "404.html")

        # 获取列表页的总页数
        num_pages = paginator.num_pages

        content = {
            "cate_dict": cate_dict,
            "categories": categories_dict,
            "categorys": categorys,
            "sort": sort,
            'page_skus': page_data,  # 分页后数据
            'total_page': num_pages,  # 总页数
            'page_num': page_num,  # 当前页码

        }
        return render(request, "list.html", content)


class HostView(View):
    def get(self, request, category_id):
        response = {
            "code": "0",
            "errmsg": "OK",
            "hot_skus": [],
        }
        goods_category = GoodsCategory.objects.get(id=category_id)
        sku_all = goods_category.sku_set.filter(is_launched=True).order_by("-sales")[:2]
        for sku in sku_all:
            response["hot_skus"].append({
                "id": sku.id,
                "default_image_url": sku.default_image,
                "name": sku.name,
                "price": sku.price,
            })

        return http.JsonResponse(response)


class DetailView(View):
    def get(self, request, sku_id):
        # 商品分类
        categories = category()
        # 校验当前sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return render(request, "404.html")

        # 面包屑导航
        categorys = GoodsCategory.objects.get(id=sku.category_id)
        cate_dict = breadcrumb(categorys)

        spu_options = {}
        all_skus = sku.spu.sku_set.all()
        for sku_temp in all_skus:
            one_sku_specs = sku_temp.specs.all()
            for one_sku_spec in one_sku_specs:
                if (one_sku_spec.spec.name, one_sku_spec.option.value) not in spu_options:
                    spu_options[(one_sku_spec.spec.name, one_sku_spec.option.value)] = {sku_temp.id}
                else:
                    spu_options[(one_sku_spec.spec.name, one_sku_spec.option.value)].add(sku_temp.id)
        for sp, spu_option in spu_options.items():
            if sku.id in spu_option:
                nums = spu_option - {sku.id}
                print("当前的nums----->>>", nums)
                spu_options[sp] = {sku.id}
                print("当前的字典------>>>", spu_options)
                for k, v in spu_options.items():
                    for i in v:
                        if i in nums:
                            spu_options[k] = {i}

        new_dict = {}
        for k, v in spu_options.items():
            if k[0] not in new_dict:
                new_dict[k[0]] = [(k[1], v.pop())]
            else:
                new_dict[k[0]].append((k[1], v.pop()))

        # 存储浏览记录
        user_id = request.user.id
        redis_con = get_redis_connection("history")
        pipeline = redis_con.pipeline()
        # 去重
        pipeline.lrem("history_%s" % user_id, 0, sku.id)
        # 添加
        pipeline.lpush("history_%s" % user_id, sku.id)
        # 最后截取
        pipeline.ltrim("history_%s" % user_id, 0, 4)
        # 执行管道
        pipeline.execute()

        context = {
            "categories": categories,
            "sku": sku,
            "cate_dict": cate_dict,
            "spu_options": new_dict,
        }

        return render(request, "detail.html", context)
